<template>
  <el-dialog
    :title="$t('project.createTask')"
    v-model="dialogVisible"
    width="600px"
    :close-on-click-modal="false"
    :before-close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-position="top"
      v-loading="loading"
    >
      <!-- 任务标题 -->
      <el-form-item :label="$t('project.taskTitle')" prop="title">
        <el-input 
          v-model="form.title" 
          :placeholder="$t('project.taskTitlePlaceholder')"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>

      <!-- 任务描述 -->
      <el-form-item :label="$t('project.taskDescription')" prop="description">
        <el-input 
          v-model="form.description" 
          type="textarea" 
          :rows="4"
          :placeholder="$t('project.taskDescriptionPlaceholder')"
          maxlength="1000"
          show-word-limit
        />
      </el-form-item>

      <!-- 任务优先级和分配者 -->
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item :label="$t('project.priority')" prop="priority">
            <el-select 
              v-model="form.priority" 
              class="w-100"
              :placeholder="$t('project.priorityPlaceholder')"
            >
              <el-option
                v-for="priority in priorityOptions"
                :key="priority.value"
                :label="priority.label"
                :value="priority.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('project.assignee')" prop="assigneeId">
            <el-select 
              v-model="form.assigneeId" 
              class="w-100"
              :placeholder="$t('project.assigneePlaceholder')"
              filterable
              clearable
            >
              <el-option
                v-for="member in teamMembers"
                :key="member.userId"
                :label="member.username || member.nickname || `用户${member.userId}`"
                :value="member.userId"
              >
                <div class="member-option">
                  <el-avatar :size="24" :src="member.avatarUrl">
                    {{ (member.username || member.nickname || 'U')?.charAt(0).toUpperCase() }}
                  </el-avatar>
                  <span>{{ member.username || member.nickname || `用户${member.userId}` }}</span>
                  <el-tag size="small" v-if="member.role === 'OWNER'">
                    {{ $t('team.role.owner') }}
                  </el-tag>
                  <el-tag size="small" v-else-if="member.role === 'ADMIN'">
                    {{ $t('team.role.admin') }}
                  </el-tag>
                </div>
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 截止日期和预估工时 -->
      <el-row :gutter="16">
        <el-col :span="12">
          <el-form-item :label="$t('project.dueDate')" prop="dueDate">
            <el-date-picker
              v-model="form.dueDate"
              type="datetime"
              :placeholder="$t('project.dueDatePlaceholder')"
              class="w-100"
              :disabled-date="disabledDate"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('project.estimatedHours')" prop="estimatedHours">
            <el-input-number
              v-model="form.estimatedHours"
              :min="0"
              :max="999"
              :step="0.5"
              :precision="1"
              class="w-100"
              :placeholder="$t('project.estimatedHoursPlaceholder')"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <!-- 任务标签 -->
      <el-form-item :label="$t('project.taskTags')" prop="tags">
        <el-select
          v-model="form.tags"
          multiple
          filterable
          allow-create
          default-first-option
          :reserve-keyword="false"
          :placeholder="$t('project.taskTagsPlaceholder')"
          class="w-100"
        >
          <el-option
            v-for="tag in commonTags"
            :key="tag"
            :label="tag"
            :value="tag"
          />
        </el-select>
      </el-form-item>

      <!-- 任务依赖 -->
      <el-form-item :label="$t('project.taskDependencies')" prop="dependencies">
        <el-select
          v-model="form.dependencies"
          multiple
          filterable
          :placeholder="$t('project.taskDependenciesPlaceholder')"
          class="w-100"
        >
          <el-option
            v-for="task in availableTasks"
            :key="task.id"
            :label="task.title"
            :value="task.id"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="loading">
          {{ $t('common.create') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { taskApi } from '@/api/project'
import type { TaskCreateRequest, Task } from '@/types/project'
import { TaskPriority } from '@/types/project'

// Props
interface Props {
  modelValue: boolean
  projectId: number | null
  teamMembers: Array<{
    userId: number
    userName: string
    userAvatar?: string
    role: string
    status: string
  }>
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:modelValue': [value: boolean]
  'success': []
}>()

const { t } = useI18n()

// 响应式数据
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()
const loading = ref(false)
const availableTasks = ref<Task[]>([])
const form = ref<TaskCreateRequest & { tags: string[], dependencies: number[] }>({
  projectId: props.projectId || 0,
  title: '',
  description: '',
  priority: TaskPriority.MEDIUM,
  assigneeId: undefined,
  dueDate: undefined,
  estimatedHours: undefined,
  tags: [],
  dependencies: []
})

// 计算属性
const priorityOptions = computed(() => [
  { value: TaskPriority.LOW, label: t('project.priority.low') },
  { value: TaskPriority.MEDIUM, label: t('project.priority.medium') },
  { value: TaskPriority.HIGH, label: t('project.priority.high') },
  { value: TaskPriority.URGENT, label: t('project.priority.urgent') }
])

const commonTags = computed(() => [
  t('project.tags.frontend'),
  t('project.tags.backend'),
  t('project.tags.database'),
  t('project.tags.ui'),
  t('project.tags.api'),
  t('project.tags.testing'),
  t('project.tags.documentation'),
  t('project.tags.bugfix'),
  t('project.tags.feature'),
  t('project.tags.optimization')
])

// 表单验证规则
const rules = computed<FormRules>(() => ({
  title: [
    { required: true, message: t('project.taskTitleRequired'), trigger: 'blur' },
    { min: 2, max: 200, message: t('project.taskTitleLength'), trigger: 'blur' }
  ],
  description: [
    { max: 1000, message: t('project.taskDescriptionLength'), trigger: 'blur' }
  ],
  priority: [
    { required: true, message: t('project.priorityRequired'), trigger: 'change' }
  ],
  estimatedHours: [
    { 
      validator: (rule, value, callback) => {
        if (value !== undefined && (value < 0 || value > 999)) {
          callback(new Error(t('project.estimatedHoursRange')))
        } else {
          callback()
        }
      }, 
      trigger: 'change' 
    }
  ]
}))

// 方法
const disabledDate = (time: Date) => {
  // 不能选择过去的日期
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

const fetchAvailableTasks = async () => {
  if (!props.projectId) return
  
  try {
    const response = await taskApi.getProjectTasks(props.projectId)
    availableTasks.value = (response.data || []).filter(task => 
      task.status !== 'COMPLETED' && task.status !== 'CANCELLED'
    )
  } catch (error) {
    console.error('获取可用任务失败:', error)
  }
}

const handleClose = () => {
  dialogVisible.value = false
  resetForm()
}

const resetForm = () => {
  formRef.value?.resetFields()
  form.value = {
    projectId: props.projectId || 0,
    title: '',
    description: '',
    priority: TaskPriority.MEDIUM,
    assigneeId: undefined,
    dueDate: undefined,
    estimatedHours: undefined,
    tags: [],
    dependencies: []
  }
}

const handleSubmit = async () => {
  if (!formRef.value || !props.projectId) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      loading.value = true
      
      // 格式化数据
      const formData = {
        ...form.value,
        projectId: props.projectId!
      }
      
      // 移除前端扩展字段
      delete formData.tags
      delete formData.dependencies
      
      await taskApi.createTask(formData)
      
      ElMessage.success(t('project.createTaskSuccess'))
      emit('success')
      handleClose()
    } catch (error) {
      console.error('创建任务失败:', error)
      ElMessage.error(t('project.createTaskError'))
    } finally {
      loading.value = false
    }
  })
}

// 监听projectId变化
watch(() => props.projectId, (newId) => {
  if (newId) {
    form.value.projectId = newId
  }
})

// 监听对话框打开
watch(dialogVisible, (visible) => {
  if (visible && props.projectId) {
    fetchAvailableTasks()
  }
})
</script>

<style scoped lang="scss">
.w-100 {
  width: 100%;
}

.member-option {
  display: flex;
  align-items: center;
  gap: 8px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
